<link rel="stylesheet" type="text/css" href="{$GLOBALS.site_url}/system/ext/jquery/css/jquery-ui.css" />
{if $smarty.get.lightbox}
<script language="JavaScript" type="text/javascript" src="{$GLOBALS.site_url}/system/ext/jquery/jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="{$GLOBALS.site_url}/system/ext/jquery/jquery-ui.js"></script>
<script language="JavaScript" type="text/javascript" src="{$GLOBALS.site_url}/system/ext/jquery/jquery.bgiframe.js"></script>
<script language="JavaScript" type="text/javascript" src="{$GLOBALS.site_url}/system/ext/jquery/jquery.form.js"></script>
<script type="text/javascript">
        {literal}
        $.ui.dialog.defaults.bgiframe = true;
        function submitForm(id) {
            lpp = document.getElementById("listings_per_page" + id);
            location.href = '?{/literal}searchId={$searchId}{literal}&action=search&page=1&listings_per_page=' + lpp.value;
    }

    function popUpWindow(url, widthWin, heightWin, title, parentReload, userLoggedIn){
        reloadPage = false;
        newPageReload = false;
        $("#messageBox").dialog( 'destroy' ).html('{/literal}<img style="vertical-align: middle" src="{$GLOBALS.site_url}/system/ext/jquery/progbar.gif" alt="[[Please, wait ...]]" /> [[Please, wait ...]]{literal}');
        $("#messageBox").dialog({
            width: widthWin,
            height: heightWin,
            modal: true,
            title: title,
            close: function(event, ui) {
                if((parentReload == true) && !userLoggedIn || newPageReload == true) {
                    if(reloadPage == true)
                        parent.document.location.reload();
                }
            }
        }).dialog( 'open' );
        $.get(url, function(data){
            $("#messageBox").html(data);
        });
        return false;
    }

    function SaveAd(noteId, url) {
        $.get(url, function(data){
            $("#"+noteId).html(data);
        });
    }

    {/literal}
</script>
<div id="messageBox"></div>
{/if}

<!-- GOOGLE MAP SEARCH RESULTS -->
<div id="map"></div>
<!-- END OF GOOGLE MAP SEARCH RESULTS -->

<!-- GOOGLE MAP SECTION -->
{literal}

<style>
    .markerInfoWindow {padding: 5px 20px;}
</style>

<script src="http://maps.google.com/maps/api/js?v=3.3&sensor=false" type="text/javascript"></script>
    <!--<script type="text/javascript" src="{/literal}{$GLOBALS.site_url}{literal}/system/ext/GoogleMapsUtilityLib/markerclusterer/src/markerclusterer.js"></script>-->
<script type="text/javascript"><!--
//<![CDATA[

function xmlParse(str) {
    if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    }
    if (typeof DOMParser != 'undefined') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
    }
    return createElement('div', null);
}

// function to check current Zoom of map, and show or hide united markers
function checkZoom(map, markersUnitiesArray) {
    var mapZoom = map.getZoom();
    // this value - it clusterer zoom value
    if (mapZoom > 10) {
        for (var i in markersUnitiesArray) {
            markersUnitiesArray[i].setVisible(true);
        }
    } else {
        for (var i in markersUnitiesArray) {
            markersUnitiesArray[i].setVisible(false);
        }
    }
}

/*var clustererURL = '{/literal}{$GLOBALS.site_url}{literal}/system/ext/GoogleMapsUtilityLib/markerclusterer/';
	var styles = [ [{
	    url: clustererURL + 'images/people35.png',
	    height: 35,
	    width: 35,
	    opt_anchor: [16, 0],
	    opt_textColor: '#ff00ff',
	    opt_textSize: 10
    }, {
	    url: clustererURL + 'images/people45.png',
	    height: 45,
	    width: 45,
	    opt_anchor: [24, 0],
	    opt_textColor: '#ff0000',
	    opt_textSize: 11
    }, {
	    url: clustererURL + 'images/people55.png',
	    height: 55,
	    width: 55,
	    opt_anchor: [32, 0],
	    opt_textSize: 12
    }], [{
	    url: clustererURL + 'images/conv30.png',
	    height: 27,
	    width: 30,
	    anchor: [3, 0],
	    textColor: '#ff00ff',
	    opt_textSize: 10
    }, {
	    url: clustererURL + 'conv40.png',
	    height: 36,
	    width: 40,
	    opt_anchor: [6, 0],
	    opt_textColor: '#ff0000',
	    opt_textSize: 11
    }, {
	    url: clustererURL + 'conv50.png',
	    width: 50,
	    height: 45,
	    opt_anchor: [8, 0],
	    opt_textSize: 12
    }], [{
	    url: clustererURL + 'heart30.png',
	    height: 26,
	    width: 30,
	    opt_anchor: [4, 0],
	    opt_textColor: '#ff00ff',
	    opt_textSize: 10
    }, {
	    url: clustererURL + 'heart40.png',
	    height: 35,
	    width: 40,
	    opt_anchor: [8, 0],
	    opt_textColor: '#ff0000',
	    opt_textSize: 11
    }, {
	    url: clustererURL + 'heart50.png',
	    width: 50,
	    height: 44,
	    opt_anchor: [12, 0],
	    opt_textSize: 12
    }] ];*/

var markersArray = [];
var markersData;
var mapZoom = 11;

var infoWindows = [];
var markersStorage = {};

function addMarkerToStorageCounter(marker, lat, lng) {
    var elemID = lat.toString() + lng.toString();
    if (typeof(markersStorage[elemID]) != 'undefined') {
        markersStorage[elemID].push(marker);
    } else {
        markersStorage[elemID] =  new Array();
        markersStorage[elemID].push(marker);
    }
}

function load(markersXmlData, divId, markersCache) {
    var myLatlng = new google.maps.LatLng(47.814495, -122.411861);
    var myOptions = {
        zoom: mapZoom,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(divId), myOptions);

    if (markersXmlData != null && markersXmlData != '<markers></markers>') {
        var data    = markersXmlData;
        markersData = markersXmlData;

        var lat_max, lat_min, lng_max, lng_min;
        var xml     = xmlParse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        var counter = 0;

        // set map center to first marker
        map.setCenter(new google.maps.LatLng( markers[0].getAttribute("lat"), markers[0].getAttribute("lng")));

        //var markersArray = [];
        var markersUnitiesArray = [];
        for (var i = 0; i < markers.length; i++) {
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));

            // skip marker if no coordinates for it
            if (isNaN(lat) == false && isNaN(lng) == false) {
                if (lat > lat_max || lat_max == undefined) {
                    lat_max = lat;
                }
                if (lat < lat_min || lat_min == undefined) {
                    lat_min = lat;
                }
                if (lng > lng_max || lng_max == undefined) {
                    lng_max = lng;
                }
                if (lng < lng_min || lng_min == undefined) {
                    lng_min = lng;
                }

                var text    = markers[i].firstChild.nodeValue;
                var type    = markers[i].getAttribute("type");
                var point   = new google.maps.LatLng(lat,lng);
                // i+1 - number of marker by order
                var num = i+1;
                var marker  = createMarker(map, point, text, type, num, markersCache);

                // add marker to storage of unions
                addMarkerToStorageCounter(marker, lat, lng);
                // add to markers of map (need for clustering)
                markersArray.push(marker);
                counter++;
            }
        }

        // OK. GET UNION STORAGE AND SEEK FOR MARKERS, PLACED IN ONE POSITION
        // MAKE ONE UNITY MARKER FOR IT
        for (var i in markersStorage) {
            // console.log(i, markersStorage[i].length);
            if (markersStorage[i].length > 1) {
                var position;
                var unionText = '';
                for (var j in markersStorage[i]) {
                    //console.log( markersStorage[i][j].markerText );
                    var inMarker = markersStorage[i][j];
                    inMarker.setVisible(false);

                    position  = inMarker.getPosition();
                    unionText = unionText + inMarker.markerText + "<hr color=\"#000000\" />";
                }

                var type   = 'union';
                var marker = createMarker(map, position, unionText, type, '', markersCache);

                markersUnitiesArray.push(marker);
            }
        }

        var lat_max_abs = Math.abs(lat_max);
        var lat_min_abs = Math.abs(lat_min);
        var lng_max_abs = Math.abs(lng_max);
        var lng_min_abs = Math.abs(lng_min);

        var lat_diff = Math.abs(lat_max_abs-lat_min_abs);
        var lng_diff = Math.abs(lng_max_abs-lng_min_abs);

        map.panTo( new google.maps.LatLng( lat_min+(lat_diff/2), lng_min+(lng_diff/2)) );

        var bounds = new google.maps.LatLngBounds( new google.maps.LatLng(lat_min, lng_min), new google.maps.LatLng(lat_max, lng_max) );
        map.fitBounds(bounds);

        /*
        var zoom = parseInt(document.getElementById('zoom').value, 10);
        var size = parseInt(document.getElementById('size').value, 10);
        var style = parseInt(document.getElementById('style').value, 10);
        */
        var zoom = 10;
        var size = 50;
        var style = 10;
        zoom = zoom == -1 ? null : zoom;
        size = size == -1 ? null : size;
        style = style == -1 ? null: style;

        /*markerClusterer = new MarkerClusterer(map, markersArray, {
            maxZoom: zoom,
            gridSize: size,
            styles: styles[style]
        });*/

        // check current zoom of map, and show or hide united markers
        checkZoom(map, markersUnitiesArray);

        // ADD EVENT LISTENER TO CHECK VALUE OF MAP ZOOM
        google.maps.event.addListener(map, 'zoom_changed', function() {
            checkZoom(map, markersUnitiesArray);
        });
    }
}


function createMarker(map, posLatLng, text, type, orderNum, markersCache) {
    var contentString = '<div class="markerInfoWindow">'+
        text +
        '</div>';
    var infoWindow = new google.maps.InfoWindow({
        content: contentString
    });
    infoWindows.push(infoWindow);
    /*var icon = '';
    if (orderNum && $.isArray(markersCache)) {
        var markerCache = 'marker_' + type + '_' + orderNum + '.gif';
        if ($.inArray(markerCache, markersCache) != -1) {
            icon = '{/literal}{$GLOBALS.site_url}{literal}/system/cache/markers/' + markerCache;
        } else {
        icon = "{/literal}{$GLOBALS.site_url}{literal}/system/miscellaneous/get_image_marker/?type=" + type + "&text=" + orderNum;
        }
    } else if (orderNum) {
        icon = "{/literal}{$GLOBALS.site_url}{literal}/system/miscellaneous/get_image_marker/?type=" + type + "&text=" + orderNum;
    }*/
    var marker = new google.maps.Marker({
        position: posLatLng,
        map: map,
        title: '',
        icon:  '',
        flat: true,
        markerText: contentString,
        optimized: false
    });
    google.maps.event.addListener(marker, 'click', function() {
        for (var i = 0; i < infoWindows.length; i++) {
            infoWindows[i].close();
        }
        infoWindow.open(map,marker);
    });
    google.maps.event.addListener(infoWindow, 'closeclick', function(){
        var my_content = infoWindow.getContent();
        var id = my_content.replace(/.+<span id="notes_(\d+)".+>/, '$1');
        var note = $('#notes_'+id).html();
        infoWindow.setContent(my_content.replace(/(<span.+)<a.+<\/a>.+(<\/span>)/g, '$1'+note+'$2'));
    });
    return marker;
}

{/literal}
// FOR GOOGLE MAP CODE
var mapListings = '<markers>' +
{foreach from=$listings item=listing name=listings}
    {if $listing.latitude && $listing.longitude}
        {if $listing.type.id != 'Resume'}
            '<marker lat="{$listing.latitude}" lng="{$listing.longitude}" type="{if $listing.api}{$listing.api}{elseif $listing.priority}priority{else}{$listing.type.id}{/if}" ><![CDATA[' +
            "<h3><a href=\"{$GLOBALS.site_url}/display-job/{$listing.id}/{$listing.Title|regex_replace:"/[\\/\\\:*?\"<>|%#$\s]/":"-"}.html?searchId={$searchId}&amp;page={$listing_search.current_page}\" target=\"_blank\"><strong>{$listing.Title}</strong></a></h3>" +
            "<strong>Company:</strong> " +
            {if $listing.company_name}
                '<a href="{$GLOBALS.site_url}/search-results-jobs/?action=search&amp;username[equal]={$listing.user.id}&amp;company_name[equal]={$listing.company_name}">{$listing.company_name}</a>' +
                {else}
                {if strpos($listing.user.CompanyName, '-') !== false}
                    '<a href="{$GLOBALS.site_url}/search-results-jobs/?action=search&amp;username[equal]={$listing.user.id}">{$listing.user.CompanyName}</a>' +
                    {else}
                    '<a href="{$GLOBALS.site_url}/company/{$listing.user.id}/{$listing.user.CompanyName|replace:" ":"-"|escape:"url"}">{$listing.user.CompanyName}</a>' +
                {/if}
            {/if}
            '<br />' +
            '<strong>City:</strong> {$listing.City}<br />' +
            '<hr color="#DDDDDD" />' +
            '<span id="notes_{$listing.id}">' +
            {if $listing.saved_listing &&  $acl->isAllowed('save_job')}
                {if $listing.saved_listing.note && $listing.saved_listing.note != ''}
                    '<a href="{$GLOBALS.site_url}/edit-notes/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/edit-notes/?listing_sid={$listing.id}&amp;view=map\', 500, 200, \'[[Edit notes]]\'); return false;"  class="action">[[Edit notes]]</a>&nbsp;&nbsp;' +
                    {else}
                    '<a href="{$GLOBALS.site_url}/add-notes/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/add-notes/?listing_sid={$listing.id}&amp;view=map\', 500, 200, \'[[Add notes]]\'); return false;"  class="action">[[Add notes]]</a>&nbsp;&nbsp;' +
                {/if}
                {else}
                {if $acl->isAllowed("save_job")}
                    '<a href="{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}" onclick="{if $GLOBALS.current_user.logged_in}SaveAd(\'notes_{$listing.id}\', \'{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}&listing_type=job&amp;view=map\'){else}popUpWindow(\'{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}&listing_type=job\', 300, 300, \'Save this Job\', true, {if $GLOBALS.current_user.logged_in}true{else}false{/if}){/if}; return false;" class="action">[[Save ad]]</a>&nbsp;&nbsp;' +
                    {elseif $acl->getPermissionParams("save_job") == "message"}
                    '<a href="{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/access-denied/?permission=save_job\', 300, 300, \'[[Save ad]]\'); return false;" class="action">[[Save ad]]</a>&nbsp;&nbsp;' +
                {/if}
            {/if}
            '</span>' +
            "<a href=\"{$GLOBALS.site_url}/display-job/{$listing.id}/{$listing.Title|regex_replace:"/[\\/\\\:*?\"<>|%#$\s]/":"-"}.html?searchId={$searchId}&amp;page={$listing_search.current_page}\" target=\"_blank\">[[View job details]]</a>" +
            {elseif $listing.type.id == 'Resume'}
            '<marker lat="{$listing.latitude}" lng="{$listing.longitude}" type="{$listing.type.id}" ><![CDATA[' +
            '<strong>Name:</strong> {if $listing.anonymous == 1}[[Anonymous User]]{else}{$listing.user.FirstName} {$listing.user.LastName}{/if}' +
            "<h3><a href=\"{$GLOBALS.site_url}/display-resume/{$listing.id}/{$listing.Title|regex_replace:"/[\\/\\\:*?\"<>|%#$\s]/":"-"}.html?searchId={$searchId}&amp;page={$listing_search.current_page}\" target=\"_blank\"><strong>{$listing.Title}</strong></a></h3>" +
            '<strong>City:</strong> {$listing.City}<br />' +
            '<span id="notes_{$listing.id}">' +
            {if $listing.saved_listing && $acl->isAllowed('save_resume')}
                {if $listing.saved_listing.note && $listing.saved_listing.note != ''}
                    '<a href="{$GLOBALS.site_url}/edit-notes/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/edit-notes/?listing_sid={$listing.id}&amp;view=map\', 500, 200, \'[[Edit notes]]\'); return false;"  class="action">[[Edit notes]]</a>&nbsp;&nbsp;' +
                    {else}
                    '<a href="{$GLOBALS.site_url}/add-notes/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/add-notes/?listing_sid={$listing.id}&amp;view=map\', 500, 200, \'[[Add notes]]\'); return false;"  class="action">[[Add notes]]</a>&nbsp;&nbsp;' +
                {/if}
                {else}
                {if $acl->isAllowed('save_resume')}
                    '<a href="{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}" onclick="{if $GLOBALS.current_user.logged_in}SaveAd(\'notes_{$listing.id}\', \'{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}&listing_type=resume&amp;view=map\'){else}popUpWindow(\'{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}&listing_type=resume\', 300, 300, \'[[Save this Resume]]\', true, {if $GLOBALS.current_user.logged_in}true{else}false{/if}){/if}; return false;"  class="action">[[Save ad]]</a>&nbsp;&nbsp;' +
                    {elseif $acl->getPermissionParams("save_resume") == "message"}
                    '<a href="{$GLOBALS.site_url}/saved-ads/?listing_id={$listing.id}" onclick="popUpWindow(\'{$GLOBALS.site_url}/access-denied/?permission=save_resume\', 300, 300, \'[[Save ad]]\'); return false;"  class="action">[[Save ad]]</a>&nbsp;&nbsp;' +
                {/if}
            {/if}
            '</span>' +
            "<a href=\"{$GLOBALS.site_url}/display-resume/{$listing.id}/{$listing.Title|regex_replace:"/[\\/\\\:*?\"<>|%#$\s]/":"-"}.html?searchId={$searchId}&amp;page={$listing_search.current_page}\" target=\"_blank\">[[View resume details]]</a>" +
        {/if}
        ']]></marker>' +
        '\n' +
    {/if}
{/foreach}
    '</markers>';
{literal}

/*$(function() {
$.get('{/literal}{$GLOBALS.site_url}{literal}/system/miscellaneous/get_image_marker/', function(data){
            data = $.parseJSON(data);
            load(mapListings, "map", data);
        });

    });*/

load(mapListings, "map", '');

//]]>-->
</script>
{/literal}
<!-- END OF GOOGLE MAP SECTION -->

{* load scripts for used api *}
{*{if $api}
    {if $api_used_indeed}
    <script type="text/javascript" src="http://www.indeed.com/ads/apiresults.js"></script>
    {/if}
    {if $api_used_simplyHired}
    <script type="text/javascript" src="http://api.{$GLOBALS.settings.simplyHiredSiteUrl}/c/jobs-api/js/xml-v2.js"></script>
    {/if}
{/if}*}